package com.jeesite.modules.task;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jeesite.common.cache.JedisUtils;
import com.jeesite.modules.goods.entity.*;
import com.jeesite.modules.goods.service.*;
import com.jeesite.modules.jdProduct.dao.dto.ServiceDetailInfoDto;
import com.jeesite.modules.jdProduct.entity.DelayOrder;
import com.jeesite.modules.jdProduct.entity.ZtAfterSale;
import com.jeesite.modules.jdProduct.service.DelayOrderService;
import com.jeesite.modules.jdProduct.service.ZtAfterSaleService;
import com.jeesite.modules.jdProduct.utils.AfterSaleUtils;
import com.jeesite.modules.jdProduct.utils.GsonUtil;
import com.jeesite.modules.jdProduct.utils.ProductPoolUtils;
import com.jeesite.modules.jdProduct.vo.ProductStateMessagePo;
import com.jeesite.modules.pay.totalPay.restController.NativePayController;
import com.jeesite.modules.xcxAdmin.entity.ZtAdmin;
import com.jeesite.modules.xcxAdmin.service.ZtAdminService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

@Component
@Configuration      //1.主要用于标记配置类，兼备Component的效果。
@EnableScheduling   // 2.开启定时任务
public class TaskUtils {
    @Autowired
    private ZtGoodsOrderService ztGoodsOrderService;

    @Autowired
    private ProductPoolUtils productPoolUtils;

    @Autowired
    private ZtOrderService ztOrderService;

    @Autowired
    private NativePayController nativePayController;

    @Autowired
    private ZtGoodsService ztGoodsService;

    @Autowired
    private ZtAdminService ztAdminService;

    @Autowired
    private ZtFinancialService ztFinancialService;

    @Autowired
    private DelayOrderService delayOrderService;

    @Autowired
    private ZtJDorderService ztJDorderService;

    @Autowired
    private GoodsTypeService goodsTypeService;

    @Autowired
    private ZtAfterSaleService ztAfterSaleService;
    /**
     * 一小时后下单
     */
    @Scheduled(cron = "0 0/2 * * * ?")
    private void cancelProductOrder() {
        DelayOrder delayOrder = new DelayOrder();
        delayOrder.setStatus("0");
        List<DelayOrder> orderList = delayOrderService.findByStatus(delayOrder);
        for (DelayOrder order : orderList) {
            if (System.currentTimeMillis() > order.getExpireTime()) {
                JSONObject resultJO = ProductPoolUtils.orderUniteSubmit(order.getContent());
                if (resultJO != null) {
                    //下单成功或者重新下单,重新保存信息
                    if(resultJO.getBoolean("success")||resultJO.getString("resultCode").equals("0008")){
                        JSONObject result = resultJO.getJSONObject("result");
                        String jdOrderId = result.get("jdOrderId").toString();
                        double orderPrice = result.getDouble("orderPrice");
                        double freight = result.getDouble("freight");
                        JSONArray jna = result.getJSONArray("sku");
                        List<ZtGoodsOrder> ztGoodsOrderList = new ArrayList<ZtGoodsOrder>();
                        if (jna != null && jna.size() > 0) {
                            for (int i = 0; i < jna.size(); i++) {
                                JSONObject jct = jna.getJSONObject(i);
                                double p = jct.getDouble("price");
                                String sku = jct.get("skuId").toString();
                                int num = jct.getInteger("num");
                                ZtGoodsOrder ztGoodsOrder = new ZtGoodsOrder();
                                ztGoodsOrder.setOrder(order.getOrder());
                                ztGoodsOrder.setChannelorder(jdOrderId);
                                ztGoodsOrder.setSku(sku);
                                ztGoodsOrder.setChannelprice(p);
                                ztGoodsOrder.setChannelPorder(jdOrderId);//主订单
                                ztGoodsOrder.setOrderstatus("2");
                                ztGoodsOrderList.add(ztGoodsOrder);
                            }
                            ZtOrder ztOrder = new ZtOrder();
                            ztOrder.setOrder(order.getOrder());
                            ztOrder = ztOrderService.findByOrder(ztOrder);
                            ztOrder.setOrderstatus("2");
                            ztOrderService.update(ztOrder);
                            //
                            ztGoodsOrderService.batchUpdateChannel(ztGoodsOrderList);

                        }
                        boolean isOccupyStock = ProductPoolUtils.occupyStock(jdOrderId);//确认订单

                        if (isOccupyStock) {
                            Date da = new Date();
                            ZtJDorder ztJDorder = new ZtJDorder();
                            ztJDorder.setOrder(order.getOrder());
                            ztJDorder.setFreight(freight);
                            ztJDorder.setGoods(jna.toString());
                            ztJDorder.setCreateDate(da);
                            ztJDorder.setPayTime(da);
                            ztJDorder.setJdorderid(jdOrderId);
                            ztJDorderService.save(ztJDorder);
                            order.setStatus("1");
                            delayOrderService.updateStatus(order);
                        }else {
                            orderFailed(order);
                        }
                    }else {
                        orderFailed(order);
                    }
                }
            }
        }
    }

    public void orderFailed(DelayOrder order){
        //下单失败 退款处理

        ZtGoodsOrder ztGoodsOrder = new ZtGoodsOrder();
        ztGoodsOrder.setOrder(order.getOrder());
        List<ZtGoodsOrder> goodsOrders = ztGoodsOrderService.findByOrder(ztGoodsOrder);
        for (ZtGoodsOrder goodsOrder : goodsOrders) {
            goodsOrder.setOrderstatus("6");
            ztGoodsOrderService.update(goodsOrder);
            /* balanceDetail(2, goodsOrder);*/
            forBalance(goodsOrder);
        }
        ZtOrder ztOrder = new ZtOrder();
        ztOrder.setOrder(order.getOrder());
        ztOrder = ztOrderService.getByOrder(ztOrder);
        ZtAdmin admin = ztAdminService.get(ztOrder.getZtAdmin());
        admin.setCashAmount(admin.getCashAmount() + (ztOrder.getOrigPrice() + ztOrder.getFreight()));
        admin.setAmount(admin.getAmount() - ztOrder.getBalance());
        ztAdminService.update(admin);
        order.setStatus("2");
        delayOrderService.updateStatus(order);
        ztOrder.setOrderstatus("4");
        ztOrderService.updateOrderstatus(ztOrder);
    }

 /*   private void balanceDetail(Integer type, ZtGoodsOrder ztGoodsOrder) {
        switch (type) {
            case 1:
                lessBalance(ztGoodsOrder, "-￥","3");
                break;
            case 2:
                lessBalance(ztGoodsOrder, "+￥","5");
                break;
            default:
                System.out.println("出错了");
        }
    }

    private void lessBalance(ZtGoodsOrder ztGoodsOrder,String str,String type) {
        if(ztGoodsOrder.getBalance() >0D){
            ZtFinancial ztFinancial=new ZtFinancial();
            ztFinancial.setType(type);
            ztFinancial.setContent("商品订单-"+ztGoodsOrder.getZtGoods().getTitle());
            ztFinancial.setZtAdmin(ztGoodsOrder.getZtAdmin());
            ztFinancial.setPricestr(str + ztGoodsOrder.getBalance());
            ztFinancial.setPrice(ztGoodsOrder.getBalance());
            ztFinancial.setCreateDate(new Date());
            ztFinancial.setUsername(ztGoodsOrder.getZtAdmin().getName());
            ztFinancial.setHeadimgurl(ztGoodsOrder.getZtAdmin().getHeadimgurl());
            ztAdminService.setNames();
            ztFinancialService.save(ztFinancial);
        }
    }

    /**
     * 3.京东订单支付失败
     */
    @Scheduled(cron = "0 0 0/1 * * ?")
    private void configureTasks() {
        productPoolUtils.messageGet(14);
    }

    //3.京东物流跟踪
    @Scheduled(cron = "0 0/27 * * * ?")
    private void orderTasks() {

        List<ZtGoodsOrder> listMap = productPoolUtils.orderTrackGet(5);
        if (listMap != null && listMap.size() > 0) {
            ztGoodsOrderService.batchUpdateState(listMap);
        }
    }


    //3.京东订单拆单
    @Scheduled(cron = "0 0/4 * * * ?")
    private void pOrder() {
        productPoolUtils.pOrder(1);

    }

    //3.待付款的轮询
    @Scheduled(cron = "0 0/3 * * * ?")
    private void notPayOrder() {
        Date date = org.apache.commons.lang3.time.DateUtils.addMinutes(new Date(), -21);
        ZtOrder ztOrder = new ZtOrder();
        ztOrder.setOrderTime(date);
        List<ZtOrder> ztOrderList = ztOrderService.getAllOrder(ztOrder);
        if (ztOrderList != null && ztOrderList.size() > 0) {
            for (ZtOrder zto : ztOrderList) {
                double bala = zto.getBalance();
                if (bala > 0) {
                    ZtAdmin ztAdmin = ztAdminService.get(zto.getZtAdmin());
                    ztAdmin.setAmount(ztAdmin.getAmount() - bala );
                    ztAdmin.setCashAmount(ztAdmin.getCashAmount() + bala);
                    ztAdminService.save(ztAdmin);
                }
            }
            ztOrderService.baseUpdateOrderstatus(ztOrderList);
        }
    }

    //3.京东价格改变
    @Scheduled(cron = "0 0/4 * * * ?")
    private void skuPrice() {

        String skuids = productPoolUtils.skuPrice(2);
        JSONArray skusPrices = productPoolUtils.getSellPrice(skuids);
        List<ZtGoods> plpList = new ArrayList<ZtGoods>();
        if (skusPrices != null && skusPrices.size() > 0) {
            for (int i = 0; i < skusPrices.size(); i++) {

                JSONObject jobjobj = skusPrices.getJSONObject(i);

                String skuId = jobjobj.get("skuId").toString();
                ZtGoods ztGoods = new ZtGoods();
                ztGoods.setCode(skuId);

                ztGoods = ztGoodsService.getByCode(ztGoods);

                //supplyPrice
                double price = jobjobj.get("price") == null ? -1 : Double.valueOf(jobjobj.get("price").toString());
                /*boolean isG = false;
                if (ztGoods.getSupplyPrice() != price) {//协议价变化
                    isG = true;
                }*/

                //origPrice
                double jdPrice = jobjobj.get("jdPrice") == null ? -1 : Double.valueOf(jobjobj.get("jdPrice").toString());

              /*  if (ztGoods.getSupplyPrice() == price && ztGoods.getOrigPrice() == jdPrice) {//京东价和协议价都没有变化
                    continue;
                }*/
                double jdsPrice = ProductPoolUtils.getJdsPrice(skuId);
                BigDecimal b1 = new BigDecimal(jdPrice);
                BigDecimal b2 = new BigDecimal(price);
                ztGoods.setSupplyPrice(price);
                if(jdsPrice>0D){
                    ztGoods.setJdSprice(jdsPrice);
                    ztGoods.setOrigPrice(jdsPrice);
                    BigDecimal b3 = new BigDecimal(String.valueOf(jdsPrice));
                    ztGoods.setDiff(Double.valueOf(new java.text.DecimalFormat("#.00").format(b3.subtract(b2).doubleValue())));
                    ztGoods.setDepo(Double.valueOf(new java.text.DecimalFormat("#.00").format(((double)price/jdsPrice)*100)));
                    if(!"2".equals(ztGoods.getTag())){//按规则定价 0是折扣定价   1是毛利额定价   2是自定义定价
                        ztGoods=TaskUtils.fixPrice(ztGoods);
                        if(ztGoods.getOrigPrice()==jdsPrice){//按实时价计算的
                            ztGoods.setJdSprice(jdsPrice);
                            ztGoods.setOrigPrice(jdPrice);
                        }
                    }
                }else {
                    ztGoods.setOrigPrice(jdPrice);
                    ztGoods.setJdSprice(jdsPrice);
                    ztGoods.setDiff(Double.valueOf(new java.text.DecimalFormat("#.00").format(b1.subtract(b2).doubleValue())));
                    ztGoods.setDepo(Double.valueOf(new java.text.DecimalFormat("#.00").format(((double)price/jdPrice)*100)));
                    if(!"2".equals(ztGoods.getTag())){//按规则定价 0是折扣定价   1是毛利额定价   2是自定义定价
                        ztGoods=TaskUtils.fixPrice(ztGoods);
                    }
                }
                plpList.add(ztGoods);

            }

            if (plpList != null && plpList.size() > 0) {
                ztGoodsService.batchUpdatePrice(plpList);
            }
        }

    }




    /**
     *  售后退款轮询
     */
    @Scheduled(cron = "0 0/30 * * * ?")
    public void refundPolling(){
        List<ZtAfterSale> inList = ztAfterSaleService.findByAfsServiceStepInList(Arrays.asList(10, 21, 22, 31, 32, 33, 34));
        ZtGoodsOrder ztGoodsOrder = new ZtGoodsOrder();
        for (ZtAfterSale list:inList){
            Map<String, Object> params = new HashMap<>();
            params.put("afsServiceId", list.getAfsServiceId());
            params.put("appendInfoSteps", Arrays.asList(1, 2, 4, 5));
            ServiceDetailInfoDto dto = ProductPoolUtils.queryServiceDetailInfo(GsonUtil.toJson(params));
            if (dto == null) {
                System.err.println(">>>>>>>>>>>>>>>>>>>售后退款轮询出错了>>>>>>>>>>>>>>>>>>>>>>>>>>");
            }
            //获取订单
            ztGoodsOrder.setId(list.getOrder());
            ztGoodsOrder = ztGoodsOrderService.get(ztGoodsOrder);

            // 退款到余额
            if (dto.getBiz_afterSale_serviceDetailInfo_query_response().getResult().getAfsServiceStep() == 40) {
                ztGoodsOrder.setSalestatus("3");
                ztGoodsOrderService.update(ztGoodsOrder);
                if(dto.getBiz_afterSale_serviceDetailInfo_query_response().getResult().getCustomerExpect()==10){
                    ZtAdmin admin = ztAdminService.get(list.getAdminId());
                    Double balance = ztGoodsOrder.getBalance()-ztGoodsOrder.getFreight();
                    Double totalPrice = ztGoodsOrder.getTotalPrice()+balance;
                    admin.setCashAmount(admin.getCashAmount() + totalPrice);
                    admin.setAmount(admin.getAmount() - balance);
                    if(balance<0D){
                        ztGoodsOrder.setTotalPrice(totalPrice);
                    }
                    ztGoodsOrder.setBalance(balance);
                    forBalance(ztGoodsOrder);
                    ztAdminService.update(admin);
                }

            }
            //取消
            if (dto.getBiz_afterSale_serviceDetailInfo_query_response().getResult().getAfsServiceStep() == 60) {
                ztGoodsOrder.setSalestatus("4");
                ztGoodsOrderService.update(ztGoodsOrder);
            }
            //处理中
            if (AfterSaleUtils.handle.contains(list.getAfsServiceStep()) && AfterSaleUtils.receipt.contains(list.getAfsServiceStep())) {
                ztGoodsOrder.setSalestatus("2");
                ztGoodsOrderService.update(ztGoodsOrder);
            }
            //客服关闭
            if (dto.getBiz_afterSale_serviceDetailInfo_query_response().getResult().getAfsServiceStep() == 20) {
                ztGoodsOrder.setSalestatus("1");
                ztGoodsOrderService.update(ztGoodsOrder);
            }
            //更新数据
            BeanUtils.copyProperties(dto.getBiz_afterSale_serviceDetailInfo_query_response().getResult(), list);
            ztAfterSaleService.update(list);
        };
    }
   
    
   /* //3.佣金结算
    @Scheduled(cron = "0 40 23 * * ?")
    private void commissionSettlement() {
    	ZtGoodsOrder ztGoodsOrder=new ZtGoodsOrder();
    	ztGoodsOrder.setOrderstatus("3");//已收货
    	ztGoodsOrder.setState("1");//1妥投   2拒收
    	Date da=new Date();
    	ztGoodsOrder.setIssueTime(DateUtil.getFirstSecond(DateUtils.addDays(da, -6)));//6天前零点时间
    	
    	List<ZtGoodsOrder> ztGoodsOrderList=ztGoodsOrderService.getJSAll(ztGoodsOrder);
    	if(ztGoodsOrderList!=null && ztGoodsOrderList.size()>0){
    		for(ZtGoodsOrder zg:ztGoodsOrderList){
    			forFinancial(zg.getZtGoods(), zg.getZtAdmin(), da, zg.getNumCount());
    			zg.setIsjs(1);
    			
    		}
    		ztGoodsOrderService.batchUpdateIsJS(ztGoodsOrderList);
    	}
    }*/

//    public void forFinancial(ZtGoods ztGoods, ZtAdmin ztAdmin, Date da, int numCount) {
//
//        String lastadminid = ztAdmin.getLastadmin();
//
//        if (StringUtils.isNotBlank(lastadminid)) {//有上级
//            //**//**一级返佣******START********//**//
//            ZtAdmin lastadmin = new ZtAdmin();
//            lastadmin.setId(lastadminid);
//            lastadmin = ztAdminService.get(lastadmin);
//            String level = lastadmin.getLevel();
//            double priceGoods = 0D;
//            String adminLevel = ztAdmin.getLevel();
//            if ("0".equals(level)) {
//                priceGoods = ztGoods.getCommonOnePrice();
//            } else if ("1".equals(level)) {
//
//                if ("0".equals(adminLevel)) {
//                    priceGoods = ztGoods.getCopperOnePrice();
//                } else if ("1".equals(adminLevel)) {
//                    priceGoods = ztGoods.getTcopperOnePrice();
//                } else if ("2".equals(adminLevel)) {
//                    priceGoods = ztGoods.getYcopperOnePrice();
//                } else if ("3".equals(adminLevel)) {
//                    priceGoods = ztGoods.getJcopperOnePrice();
//                }
//
//            } else if ("2".equals(level)) {
//
//                if ("0".equals(adminLevel)) {
//                    priceGoods = ztGoods.getSilverOnePrice();
//                } else if ("1".equals(adminLevel)) {
//                    priceGoods = ztGoods.getTsilverOnePrice();
//                } else if ("2".equals(adminLevel)) {
//                    priceGoods = ztGoods.getYsilverOnePrice();
//                } else if ("3".equals(adminLevel)) {
//                    priceGoods = ztGoods.getJsilverOnePrice();
//                }
//
//            } else if ("3".equals(level)) {
//
//                if ("0".equals(adminLevel)) {
//                    priceGoods = ztGoods.getGoldOnePrice();
//                } else if ("1".equals(adminLevel)) {
//                    priceGoods = ztGoods.getTgoldOnePrice();
//                } else if ("2".equals(adminLevel)) {
//                    priceGoods = ztGoods.getYgoldOnePrice();
//                } else if ("3".equals(adminLevel)) {
//                    priceGoods = ztGoods.getJgoldOnePrice();
//                }
//            }
//
//            BigDecimal b1 = new BigDecimal(priceGoods);
//            BigDecimal b2 = new BigDecimal(numCount);
//
//            String dff = new java.text.DecimalFormat("#.00").format(b1.multiply(b2).doubleValue());
//
//            priceGoods = Double.valueOf(dff);
//
//            //lastadmin.setAmount((lastadmin.getAmount()==null?0:lastadmin.getAmount())+priceGoods);
//            lastadmin.setCashAmount((lastadmin.getCashAmount() == null ? 0 : lastadmin.getCashAmount()) + priceGoods);
//
//            ztAdminService.save(lastadmin);
//
//            ZtFinancial ztFinancial = new ZtFinancial();
//            ztFinancial.setType("1");
//            ztFinancial.setContent("(佣金)商品订单-" + ztGoods.getTitle());
//            ztFinancial.setZtAdmin(lastadmin);
//            ztFinancial.setZtGoods(ztGoods);
//            ztFinancial.setPricestr("￥" + priceGoods);
//            ztFinancial.setPrice(priceGoods);
//            ztFinancial.setCreateDate(da);
//            ztFinancial.setUsername("(粉丝)" + ztAdmin.getUsername());
//            ztFinancial.setHeadimgurl(ztAdmin.getHeadimgurl());
//            ztAdminService.setNames();
//            ztFinancialService.save(ztFinancial);
//            //**//**一级返佣******END********//**//*
//
//            String lastTwoadminid = lastadmin.getLastadmin();
//            if (StringUtils.isNotBlank(lastTwoadminid)) {//有上级
//                //**//**二级返佣******START********//**//*
//                ZtAdmin lastTwoadmin = new ZtAdmin();
//                lastTwoadmin.setId(lastTwoadminid);
//                lastTwoadmin = ztAdminService.get(lastTwoadmin);
//                level = lastTwoadmin.getLevel();
//                priceGoods = 0D;
//                if ("0".equals(level)) {
//
//                } else if ("1".equals(level)) {
//                    if ("0".equals(adminLevel)) {
//                        priceGoods = ztGoods.getCopperTwoPrice();
//                    } else if ("1".equals(adminLevel)) {
//                        priceGoods = ztGoods.getTcopperTwoPrice();
//                    } else if ("2".equals(adminLevel)) {
//                        priceGoods = ztGoods.getYcopperTwoPrice();
//                    } else if ("3".equals(adminLevel)) {
//                        priceGoods = ztGoods.getJcopperTwoPrice();
//                    }
//
//                } else if ("2".equals(level)) {
//
//
//                    if ("0".equals(adminLevel)) {
//                        priceGoods = ztGoods.getSilverTwoPrice();
//                    } else if ("1".equals(adminLevel)) {
//                        priceGoods = ztGoods.getTsilverTwoPrice();
//                    } else if ("2".equals(adminLevel)) {
//                        priceGoods = ztGoods.getYsilverTwoPrice();
//                    } else if ("3".equals(adminLevel)) {
//                        priceGoods = ztGoods.getJsilverTwoPrice();
//                    }
//
//                } else if ("3".equals(level)) {
//
//                    if ("0".equals(adminLevel)) {
//                        priceGoods = ztGoods.getGoldTwoPrice();
//                    } else if ("1".equals(adminLevel)) {
//                        priceGoods = ztGoods.getTgoldTwoPrice();
//                    } else if ("2".equals(adminLevel)) {
//                        priceGoods = ztGoods.getYgoldTwoPrice();
//                    } else if ("3".equals(adminLevel)) {
//                        priceGoods = ztGoods.getJgoldTwoPrice();
//                    }
//
//                }
//
//                //lastTwoadmin.setAmount((lastTwoadmin.getAmount()==null?0:lastTwoadmin.getAmount())+priceGoods);
//                lastTwoadmin.setCashAmount((lastTwoadmin.getCashAmount() == null ? 0 : lastTwoadmin.getCashAmount()) + priceGoods);
//                ztAdminService.save(lastTwoadmin);
//
//                ZtFinancial ztFinancial2 = new ZtFinancial();
//                ztFinancial2.setType("2");
//                ztFinancial2.setContent("(佣金)商品订单-" + ztGoods.getTitle());
//                ztFinancial2.setZtAdmin(lastTwoadmin);
//                ztFinancial2.setPricestr("￥" + priceGoods);
//                ztFinancial2.setPrice(priceGoods);
//                ztFinancial2.setZtGoods(ztGoods);
//                ztFinancial2.setCreateDate(da);
//                ztFinancial2.setUsername(lastadmin.getUsername());
//                ztFinancial2.setHeadimgurl(lastadmin.getHeadimgurl());
//                ztAdminService.setNames();
//                ztFinancialService.save(ztFinancial2);
//                //**//**二级返佣******END********//**//
//            }
//
//        }
//    }

    public static synchronized ZtGoods fixPrice(ZtGoods ztGoods) {

        Double origPrice = ztGoods.getOrigPrice();
        Double supplyPrice = ztGoods.getSupplyPrice();

        if (supplyPrice <= 0 || supplyPrice >= origPrice) {
            ztGoods.setSjStatus("4");//自动下架
            ztGoods.setTag("3");//0是折扣定价   1是毛利额定价   2是自定义定价
            ztGoods.setState(0);
            return ztGoods;
        }
        String goodsType=ztGoods.getType();
        ZtSk ztSk=null;
        ZtMle ztMle=null;
        if(StringUtils.isNotBlank(goodsType)){
            String[] goodsTypeArr=goodsType.split(",");
            for(int ii=goodsTypeArr.length-1;ii>=0;ii--){
                String goodsCode=goodsTypeArr[ii];
                Object obj=JedisUtils.getObject("ztSkContro"+goodsCode);
                if(obj!=null){
                    ztSk=(ZtSk)obj;
                    break;
                }
            }
            for(int ii=goodsTypeArr.length-1;ii>=0;ii--){
                String goodsCode=goodsTypeArr[ii];
                Object obj=JedisUtils.getObject("ztMleContro"+goodsCode);
                if(obj!=null){
                    ztMle=(ZtMle)obj;
                    break;
                }
            }
        }
        if(ztSk==null) {
            ztSk = (ZtSk) JedisUtils.getObject("ztSkContro");
        }
        if(ztMle==null) {
            ztMle = (ZtMle) JedisUtils.getObject("ztMleContro");
        }
        double number2 = (double) (supplyPrice * 100) / origPrice;
        number2 = Double.valueOf(new java.text.DecimalFormat("#.00").format(number2));
        double switDiscount = Double.valueOf(ztSk.getSwitDiscount());
        if (number2 > switDiscount) {
            double minGross = Double.valueOf(ztMle.getMinGross());
            double mlePrice = origPrice - supplyPrice;
            if (mlePrice >= minGross) {//毛利额定价
                double memDis = Double.valueOf(ztMle.getMemPrice());
                double commonPriceDis = Double.valueOf(ztMle.getCommonPrice());

                double commonPrice = origPrice - ((mlePrice * commonPriceDis) / 100);
                commonPrice = Double.valueOf(new java.text.DecimalFormat("#.00").format(commonPrice));
                double mem = origPrice - ((mlePrice * memDis) / 100);
                mem = Double.valueOf(new java.text.DecimalFormat("#.00").format(mem));
                ztGoods.setCommonPrice(commonPrice);//普通用户价钱

                ztGoods.setDiscountPrice(mem);//会员价
                ztGoods.setDiscount(String.valueOf(
                        Double.valueOf(new java.text.DecimalFormat("#.00").format(mem / commonPrice))));

                ztGoods.setTag("1");//0是折扣定价   1是毛利额定价   2是自定义定价
                if (!"1".equals(ztGoods.getSjStatus())) {//如果没有上架
                    ztGoods.setSjStatus("3");//备上架
                }
                if( ztGoods.getState()!=null){
                    ztGoods.setState(0);//清除类目下架标志
                }
            } else {
                ztGoods.setSjStatus("4");//自动下架
                ztGoods.setTag("3");//0是折扣定价   1是毛利额定价   2是自定义定价
                ztGoods.setState(0);//清除类目下架标志
            }
        } else {//折扣
                double mem = 0;
                double memDis = 0;
                if (number2 < 40) {
                    memDis = Double.valueOf(ztSk.getMemOne());
                    mem = ((origPrice * memDis) / 100);
                } else if (number2 >= 40 && number2 < 50) {
                    memDis = Double.valueOf(ztSk.getMemTwo());
                    mem = ((origPrice * memDis) / 100);
                } else if (number2 >= 50 && number2 < 60) {
                    memDis = Double.valueOf(ztSk.getMemThree());
                    mem = ((origPrice * memDis) / 100);
                } else if (number2 >= 60 && number2 < 70) {
                    memDis = Double.valueOf(ztSk.getMemFour());
                    mem = ((origPrice * memDis) / 100);
                } else if (number2 >= 70 && number2 < 80) {
                    memDis = Double.valueOf(ztSk.getMemFive());
                    mem = ((origPrice * memDis) / 100);
                } else if (number2 >= 80 && number2 < 90) {
                    memDis = Double.valueOf(ztSk.getMemSix());
                    mem = ((origPrice * memDis) / 100);
                }
                double commonPriceDis = Double.valueOf(ztSk.getCommonPriceDis());

                double commonPrice = (origPrice * commonPriceDis) / 100;

                ztGoods.setCommonPrice(commonPrice);//普通用户价钱

                ztGoods.setDiscountPrice(mem);//会员价

                ztGoods.setDiscount(String.valueOf(Double.valueOf(new java.text.DecimalFormat("#.00").format(mem / commonPrice))));

                if (!"1".equals(ztGoods.getSjStatus())) {//如果没有上架
                    ztGoods.setSjStatus("3");
                }
                if( ztGoods.getState()!=null){
                    ztGoods.setState(0);//清除类目下架标志
                }
                ztGoods.setTag("0");//0是折扣定价   1是毛利额定价   2是自定义定价
        }
        return ztGoods;
    }
    /**
     * 明细  支出
     * @param
     * @param
     * @param
     */
    public void forBalance(ZtGoodsOrder ztGoodsOrder){
        double balance=ztGoodsOrder.getBalance();
        double total = ztGoodsOrder.getTotalPrice();
        List<ZtFinancial> list = new ArrayList<>();
        if(balance>0D){
            ZtFinancial ztFinancial=new ZtFinancial();
            ztFinancial.setAudit("2");
            ztFinancial.setType("5");
            ztFinancial.setContent("积分支付退款-"+ztGoodsOrder.getZtGoods().getTitle());
            ztFinancial.setZtAdmin(ztGoodsOrder.getZtAdmin());
            ztFinancial.setPricestr("+￥"+String.format("%.2f",balance));
            ztFinancial.setPrice(balance);
            ztFinancial.setCreateDate(new Date());
            ztFinancial.setUsername(ztGoodsOrder.getZtAdmin().getUsername());
            ztFinancial.setHeadimgurl(ztGoodsOrder.getZtAdmin().getHeadimgurl());
            ztFinancial.setPhone(ztGoodsOrder.getZtAdmin().getPhone());
            ztFinancial.setZtGoods(ztGoodsOrder.getZtGoods());
            ztFinancial.setStatus("0");
            ztFinancial.setOperation("系统");
            list.add(ztFinancial);
        }
        if(total>0D){

            ZtFinancial ztFinancial=new ZtFinancial();
            ztFinancial.setAudit("2");
            ztFinancial.setType("5");
            ztFinancial.setContent("微信支付退款-"+ztGoodsOrder.getZtGoods().getTitle());
            ztFinancial.setZtAdmin(ztGoodsOrder.getZtAdmin());
            ztFinancial.setPricestr("+￥"+String.format("%.2f",total));
            ztFinancial.setPrice(total);
            ztFinancial.setCreateDate(new Date());
            ztFinancial.setUsername(ztGoodsOrder.getZtAdmin().getUsername());
            ztFinancial.setHeadimgurl(ztGoodsOrder.getZtAdmin().getHeadimgurl());
            ztFinancial.setPhone(ztGoodsOrder.getZtAdmin().getPhone());
            ztFinancial.setZtGoods(ztGoodsOrder.getZtGoods());
            ztFinancial.setStatus("0");
            ztFinancial.setOperation("系统");
            list.add(ztFinancial);
        }
        if(list.size()>0){
            ztFinancialService.insertBatch(list);
        }
    }
    //统计类目的上下架数量
    @Scheduled(cron = "0 0 1 * * ? ")
    public void statisticalGoods(){
        List<String> goodsCodeId = goodsTypeService.getGoodsCodeId();
        List<GoodsType> list = new ArrayList<>();
        for (int i =0;i<goodsCodeId.size();i++){
            list.add(goodsTypeService.statisticalNum(goodsCodeId.get(i)));
            if((i%100)==0 && i != 0){
                goodsTypeService.statistical(list);
                list.clear();
                list=new ArrayList<GoodsType>();
            }
        }
        if(list!=null && list.size()>0){
            goodsTypeService.statistical(list);
        }
    }
    /**
     * 检测不符合售卖价格的商品
     */
    @Scheduled(cron = "30 * * * * ?")
    public void detection(){
        ztGoodsService.updateSoldOut();
    }

    /**
     *每天3点去刷新上架和备上架商品定价
     */
    @Scheduled(cron = "0 0 3 * * ?")
    public void refreshRules(){
        ExecutorService cachedThreadPool= ProductPoolUtils.cachedThreadPool;
        if(cachedThreadPool==null){
            cachedThreadPool= Executors.newCachedThreadPool();
        }
        cachedThreadPool.execute(new Runnable() {
            @Override
            public void run() {
                String [] arrStr={"1","3"};
                ZtGoods ztGoods = new ZtGoods();
                for(int j = 0;j<arrStr.length;j++){
                    ztGoods.setSjStatus(arrStr[j]);
                    ztGoods.setSpotid(1);
                    // TODO Auto-generated method stub
                    List<ZtGoods> plpList=new ArrayList<ZtGoods>();
                    List<ZtGoods> plp=ztGoodsService.findList(ztGoods);
                    String skus="";
                    for(int i=0;i<plp.size();i++){
                        if(plp.get(i).getSpotid()==1){
                            skus=plp.get(i).getCode();
                            plpList.add(ProductPoolUtils.refreshPrice(skus,plp.get(i)));//京东的商品
                        }
                        if((i%100)==0 && i != 0){
                            ztGoodsService.batchUpdatePrice(plpList);
                            plpList.clear();
                            plpList=new ArrayList<ZtGoods>();
                        }
                    }
                    if(plpList!=null && plpList.size()>0){
                        ztGoodsService.batchUpdatePrice(plpList);
                    }
                }
            }
        });

    }

    @Scheduled(cron = "0 0/10 9-22 * * ?")
    public void messageMonitor(){
        List<ProductStateMessagePo.BizMessageGetResponseBean.ResultBeanX> resultBeans = ProductPoolUtils.messageProductState("4");
        List<ZtGoods> ztGoodsList = new ArrayList<>();
        for(ProductStateMessagePo.BizMessageGetResponseBean.ResultBeanX list:resultBeans){
            ProductStateMessagePo.BizMessageGetResponseBean.ResultBeanX.ResultBean bean = list.getResult();
            ZtGoods ztGoods = new ZtGoods();
            ztGoods.setAdminLevel("0");
            ztGoods.setCode(String.valueOf(bean.getSkuId()));
            ztGoods = ztGoodsService.getByCode(ztGoods);
            if (ztGoods != null) {
                if (bean.getState() == 0) {
                    ztGoods.setSjStatus("4");
                    ztGoods.setState(0);
                }else {
                    ztGoods=ProductPoolUtils.refreshPrice(ztGoods.getCode(),ztGoods);
                }
                ztGoodsList.add(ztGoods);
            }
        }
        if(ztGoodsList.size()>0){
            ztGoodsService.batchUpdatePrice(ztGoodsList);
        }
    }
}